<?php

namespace App\Http\Controllers\Strator;

use App\Http\Controllers\Controller;
use App\Models\Strator\StratorPosition;
use App\Models\Strator\StratorPositionHasPermission;
use Illuminate\Http\Request;

class StratorPositionAuthController extends Controller
{
    //
    public function authPermission(Request $request){
        $position_id = $request->position_id;
        if(empty($position_id)){
            return $this->fail('职务角色id不能为空');
        }
        $permission_ids = $request->permission_ids;
        if(empty($permission_ids)){
            StratorPositionHasPermission::where('position_id',$position_id)->delete();
            return $this->successMsg();
        }
        if(!is_array($permission_ids)){
            return $this->fail('权限id数组格式不正确');
        }
        StratorPositionHasPermission::where('position_id',$position_id)
            ->whereNotIn('permission_id',$permission_ids)
            ->delete();
        foreach ($permission_ids as $permission_id){
            StratorPositionHasPermission::updateOrCreate([
                'position_id'=>$position_id,
                'permission_id'=>$permission_id
            ]);
        }
        return $this->successMsg();
    }

    //
    public function hasPermissionIds(Request $request){
        $position_id = $request->position_id;
        if(empty($position_id)){
            return $this->fail('职务角色id不能为空');
        }
        $missionIds = StratorPositionHasPermission::where('position_id',$position_id)->pluck('permission_id');
        return $this->success($missionIds);
    }

    //
    public function hasPermission(Request $request){
        $position_id = $request->position_id;
        if(empty($position_id)){
            return $this->fail('职务角色id不能为空');
        }
        $position = StratorPosition::find($position_id);
        if(empty($position)){
            return $this->fail('职务角色id错误');
        }
        return $this->success($position->permissions);
    }

}
